package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.KafkaConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.model.article.pojos.ApArticle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class ArtilceIsDownListener {

    @Autowired
    private ApArticleConfigService apArticleConfigService;
    @Autowired
    private ApArticleService apArticleService;

    @KafkaListener(topics = WemediaConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void onMessage(String message) {
        if (StringUtils.isNotBlank(message)) {
            Map map = JSON.parseObject(message, Map.class);
            apArticleConfigService.updateByMap(map);
            log.info("article端文章配置修改，articleId={}", map.get("articleId"));
        }
    }

    /**
     * 阅读数量加一
     *
     * @param message
     */
    @KafkaListener(topics = KafkaConstants.AP_ARTICLE_READ)
    private void like(String message) {
        //参数检查
        ApArticle apArticle = apArticleService.getById(message);
        if (apArticle != null) {
            apArticle.setViews(apArticle.getViews() + 1);
            apArticleService.updateById(apArticle);
        }
    }

    /**
     * 用户取消点赞
     *
     * @param message
     */
    @KafkaListener(topics = KafkaConstants.AP_ARTICLE_LIKE_ROLLBACK)
    private void likeRollback(String message) {
        //参数检查
        ApArticle apArticle = apArticleService.getById(message);
        if (apArticle != null ) {
            apArticle.setLikes(apArticle.getLikes() -1);
            apArticleService.updateById(apArticle);
        }
    }
    /**
     * 评论数加一
     *
     * @param message
     */
    @KafkaListener(topics = KafkaConstants.ADD_COMMENT)
    private void comment(String message) {
        //参数检查
        ApArticle apArticle = apArticleService.getById(message);
        if (apArticle != null) {
            apArticle.setComment(apArticle.getComment() + 1);
            apArticleService.updateById(apArticle);
        }
    }


}